package com.biglead.mini.config;

import com.alibaba.fastjson.JSON;
import com.biglead.mini.error.ApiException;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.nio.charset.StandardCharsets;

import static feign.FeignException.errorStatus;

@Slf4j
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        log.error("feign error, request url:{} status:{}", response.request().toString(), response.status());
        try {
            if (response.status() == HttpStatus.INTERNAL_SERVER_ERROR.value()){
                String body = IOUtils.toString(response.body().asReader(StandardCharsets.UTF_8));;
                return JSON.parseObject(body, ApiException.class);
            }
            return errorStatus(s, response);
        }
        catch (Exception e){
            return e;
        }
    }
}
